/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gestionedt.groupes;

import gestionedt.controllers.CreneauJpaController;
import gestionedt.controllers.GroupeJpaController;
import gestionedt.models.Groupe;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

/**
 * 
 */
public class SaveAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        if(isCancelled(request))
            return mapping.findForward("cancel");

        GroupesForm gForm = (GroupesForm) form;
        Groupe groupe = gForm.getGroupe();
        
        CreneauJpaController ctCreneau = new CreneauJpaController();
        int[] numsIndispo = gForm.getNumsIntIndispo();
        groupe.setIndisponibilites(ctCreneau.findCreneauxByNums(numsIndispo));

        boolean nv = (groupe.getId()==null || groupe.getId() == 0);
        GroupeJpaController ctGroupe = new GroupeJpaController();
        if(nv)
            ctGroupe.create(groupe);
        else {
            Groupe g = ctGroupe.findGroupe(groupe.getId());
            g.setLibelle(groupe.getLibelle());
            g.setEffectif(groupe.getEffectif());
            g.setIndisponibilites(groupe.getIndisponibilites());
            ctGroupe.edit(g);
        }

        return new ActionForward("/GererGroupes.do?action=afficher" +
                                         "&idGroupe="+groupe.getId(), true);
    }

}
